<template>
  <div class="address-list">
    <PageHeader title="我的地址" />

    <div class="address-empty" v-if="addresses.length === 0 && !loading">
      <van-empty description="暂无收货地址" />
      <van-button type="primary" round class="add-btn" @click="goToAdd">添加地址</van-button>
    </div>

    <van-loading v-if="loading" class="loading" vertical>加载中...</van-loading>

    <div class="address-items" v-else>
      <div
        class="address-item"
        v-for="item in addresses"
        :key="item.id"
        @click="handleAddressClick(item)"
      >
        <div class="address-item__header">
          <div class="name-phone">
            <span class="name">{{ item.name }}</span>
            <span class="phone">{{ item.phone }}</span>
          </div>
          <span class="default-tag" v-if="item.isDefault">默认</span>
        </div>
        <div class="address-item__content">{{ formatAddress(item) }}</div>
        <div class="address-item__footer">
          <div class="actions">
            <van-button size="small" plain type="primary" @click.stop="onEdit(item)">编辑</van-button>
            <van-button size="small" plain type="danger" @click.stop="onDelete(item)">删除</van-button>
          </div>
          <div class="default-switch">
            <span class="label">设为默认</span>
            <van-switch
              size="24"
              :model-value="item.isDefault"
              @click.stop
              @change="onSetDefault(item)"
            />
          </div>
        </div>
      </div>
    </div>

    <div class="fixed-bottom">
      <van-button type="primary" round block @click="goToAdd">新增地址</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast, showSuccessToast, showFailToast, showDialog } from 'vant'
import PageHeader from '@/components/PageHeader.vue'
import { getAddressList, deleteAddress, setDefaultAddress } from '@/api/address'

const router = useRouter()
const route = useRoute()
const addresses = ref<any[]>([])
const loading = ref(true)
const selectMode = computed(() => !!route.query.select)

// 格式化地址
const formatAddress = (address: any) => {
  return `${address.province} ${address.city} ${address.district} ${address.detail}`
}

// 获取地址列表
const fetchAddresses = async () => {
  loading.value = true
  try {
    const res = await getAddressList()
    if (res.code === 200 && res.data) {
      addresses.value = res.data
    } else {
      addresses.value = []
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    showFailToast('获取地址列表失败')
    addresses.value = []
  } finally {
    loading.value = false
  }
}

// 处理地址点击
const handleAddressClick = (address: any) => {
  if (selectMode.value) {
    // 选择地址模式
    router.replace({
      path: (route.query.redirect as string) || '/order/create',
      query: { addressId: address.id },
    })
  }
}

// 编辑地址
const onEdit = (address: any) => {
  router.push({
    path: '/address/edit',
    query: { id: address.id },
  })
}

// 删除地址
const onDelete = async (address: any) => {
  try {
    await showDialog({
      title: '删除地址',
      message: '确定要删除该地址吗？',
      showCancelButton: true,
    })

    const res = await deleteAddress(address.id)
    if (res.code === 200) {
      showSuccessToast('地址删除成功')
      fetchAddresses()
    } else {
      showFailToast(res.message || '删除失败')
    }
  } catch (error) {
    console.error('删除地址失败:', error)
  }
}

// 设置默认地址
const onSetDefault = async (address: any) => {
  if (address.isDefault) return

  try {
    const res = await setDefaultAddress(address.id)
    if (res.code === 200) {
      showSuccessToast('设置成功')
      fetchAddresses()
    } else {
      showFailToast(res.message || '设置失败')
    }
  } catch (error) {
    console.error('设置默认地址失败:', error)
    showFailToast('设置失败')
  }
}

// 新增地址
const goToAdd = () => {
  router.push('/address/edit')
}

// 初始化
onMounted(() => {
  fetchAddresses()
})
</script>

<style scoped lang="scss">
.address-list {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 80px;
}

.address-empty {
  padding-top: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;

  .add-btn {
    margin-top: 20px;
  }
}

.loading {
  margin-top: 100px;
}

.address-items {
  padding: 12px;
}

.address-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);

  &__header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .name-phone {
      .name {
        font-size: 16px;
        font-weight: 500;
        margin-right: 10px;
      }

      .phone {
        color: #666;
      }
    }

    .default-tag {
      padding: 2px 8px;
      background-color: #1989fa;
      color: white;
      border-radius: 4px;
      font-size: 12px;
    }
  }

  &__content {
    color: #666;
    font-size: 14px;
    line-height: 1.5;
    margin-bottom: 12px;
    word-break: break-all;
  }

  &__footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-top: 1px solid #f2f2f2;
    padding-top: 12px;

    .actions {
      display: flex;
      gap: 8px;
    }

    .default-switch {
      display: flex;
      align-items: center;

      .label {
        font-size: 14px;
        color: #666;
        margin-right: 8px;
      }
    }
  }
}

.fixed-bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 12px 16px;
  background-color: #fff;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
  z-index: 10;
}
</style> 